const express = require('express')
const passport = require('passport')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const async = require('async')
const router = express.Router()
const fs = require('fs')
const multiparty = require('multiparty')

const getCurTime = require('../../../utils/getCurTime')
const Teacher = require('../../../models/Teacher')
const Student = require('../../../models/Student')
const Course = require('../../../models/Course')
const User = require('../../../models/User')
const delArrOfOne = require('../../../utils/delArrOfOne')
const { secretOrKey, uploadURI, downloadURI } = require('../../../config/key')

/**
 * 测试接口
 */
router.get('/', (req, res) => {
  res.send('hello world')
})

/**
 * @description 用户注册接口
 * @router /api/user/register
 * @method POST
 */
router.post('/register', (req, res) => {
  // 判断用户是学生还是教师
  // 教师拥有学生的所有权限，学生只拥有学习的权限
  const userInfo = req.body

  User.findOne({
    email: userInfo.email
  })
    .then(user => {
      // 判断是否找到
      if (user) {
        // 如果找到，说明当前账户已经被注册
        return res.send({
          status: 0,
          msg: '当前账户已经存在...',
          data: null
        })
      }

      // 如果没有找到，创建一个新的学生数据
      const newUser = new User({
        email: userInfo.email,
        nickName: userInfo.nickName,
        password: userInfo.password,
        identity: userInfo.identity
      })

      // 使用bcrypt对密码进行加密
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) {
            throw err
          }

          // 给用户密码进行加密
          newUser.password = hash

          // 将新增的用户添加到数据库中
          newUser
            .save()
            .then(user => {
              if (user.identity === '学生') {
                const newStudent = new Student()
                newStudent.studentId = user._id
                newStudent
                  .save()
                  .then(student => {
                    console.log(student)
                  })
                  .catch(err => {
                    throw err
                  })
              } else {
                const newTeacher = new Teacher()
                newTeacher.teacherId = user._id
                newTeacher
                  .save()
                  .then(teacher => {
                    console.log(teacher)
                  })
                  .catch(err => {
                    throw err
                  })
              }

              res.send({
                status: 1,
                msg: '注册成功',
                data: null
              })
            })
            .catch(err => {
              throw err
            })
        })
      })
    })
    .catch(err => {
      throw err
    })
})

/**
 * @description 用户登录接口
 * @router /api/user/login
 * @method POST
 */
router.post('/login', (req, res) => {
  const userInfo = req.body
  User.findOne({
    email: userInfo.email
  })
    .then(user => {
      if (!user) {
        // 如果没有找当，返回查找失败
        return res.send({
          status: 0,
          msg: '该用户不存在，请注册...',
          data: null
        })
      }

      // 对比当前密码和系统中存储的密码是否一致
      bcrypt.compare(userInfo.password, user.password).then(isMatch => {
        if (!isMatch) {
          // 如果不一致
          return res.send({
            status: 0,
            msg: '密码错误，请重试...',
            data: null
          })
        }
        // 如果密码正确
        const rules = {
          id: user.id,
          email: user.email,
          avatar: user.avatar,
          nickName: user.nickName,
          userName: user.userName,
          gender: user.gender,
          age: user.age,
          personalized: user.personalized,
          friends: user.friends,
          applyCourse: user.applyCourse,
          shopCart: user.shopCart,
          collect: user.collect,
          myCourseNum: user.myCourseNum,
          leaveWords: user.leaveWords
        }
        jwt.sign(
          rules,
          secretOrKey,
          {
            expiresIn: '24h' // 设置token过期时间
          },
          (err, token) => {
            if (err) {
              throw err
            }
            return res.json({
              status: 1,
              msg: '登录成功',
              data: {
                my_token: `Bearer ${token}`,
                personalized: user.personalized,
                applyCourse: user.applyCourse,
                shopCart: user.shopCart,
                collect: user.collect,
                myCourseNum: user.myCourseNum,
                id: user._id,
                email: user.email,
                nickName: user.nickName,
                avatar: user.avatar,
                identity: user.identity
              }
            })
          }
        )
      })
    })
    .catch(err => {
      throw err
    })
})

/**
 * @description 查找好友接口
 * @router /api/user/findFriend
 * @method POST
 */
router.post(
  '/findFriend',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    const data = req.body

    User.findOne({
      email: data.email
    })
      .then(user => {
        if (!user) {
          ressend({
            status: 0,
            msg: '当前用户不存在，请重试...',
            data: null
          })
        }

        return res.send({
          status: 1,
          msg: '查找成功',
          data: {
            email: user.email,
            nickname: user.nickname,
            avatar: user.avatar,
            personalized: user.personalized
          }
        })
      })
      .catch(err => {
        throw err
      })
  }
)

/**
 * @description 添加好友接口
 * @router /api/user/addFriend
 * @method GET
 */
router.get(
  '/addFriend',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    const data = req.body

    User.findOne({
      email: data.friendEmail
    })
      .then(friend => {
        if (!friend) {
          return res.send({
            status: 0,
            msg: '当前用户不存在，请重试...',
            data: null
          })
        }

        User.findOne({
          email: data.myEmail
        })
          .then(user => {
            for (let i = 0; i < user.friends.length; i++) {
              if (data.friendEmail === user.friends[i].email) {
                return res.send({
                  status: 0,
                  msg: '当前当前账户已经是您的好友',
                  data: null
                })
              }
            }
            user.friends.push({
              email: friend.email,
              addDate: getCurTime(),
              userName: ''
            })

            user
              .save()
              .then(user => {
                return res.send({
                  status: 1,
                  msg: '添加成功',
                  data: {
                    email: friend.email,
                    avatar: friend.avatar,
                    nickName: friend.nickName,
                    personalized: friend.personalized,
                    identity: data.friendIdentity
                  }
                })
              })
              .catch(err => {
                console.log('save error', err)
              })
          })
          .catch(err => {
            throw err
          })
      })
      .catch(err => {
        throw err
      })
  }
)

/**
 * @description 删除好友接口
 * @router /api/user/delFriend
 * @method POST
 */
router.post(
  '/delFriend',
  passport.authenticate('jwt', {
    session: false
  }),
  (req, res) => {
    const data = req.body

    User.findOne({
      email: data.myEmail
    })
      .then(user => {
        console.log(user)
        for (let i = 0; i < user.friends.length; i++) {
          if (data.friendEmail === user.friends[i].email) {
            user.friends.splice(i, 1)
            user.save().then(user => {
              return res.send({
                status: 1,
                msg: '该好友已被删除',
                data: null
              })
            })
          }
        }
      })
      .catch(err => {
        throw err
      })
  }
)

/**
 * @description 购买课程接口
 * @router /api/user/buyCourse
 * @method GET
 */
router.get('/buyCourse', (req, res) => {
  const courseId = req.headers.courseid
  const userId = req.headers.userid
  User.findById(userId).then(user => {
    for (let i = 0; i < user.applyCourse.length; i++) {
      if (courseId === user.applyCourse[i].id.toString()) {
        return res.send({
          status: 0,
          msg: '您已报名当前课程',
          data: null
        })
      }
    }
    Course.findById(courseId)
      .then(course => {
        user.applyCourse.push({
          id: course._id,
          buyTime: getCurTime()
        })
        user.myCourseNum += 1
        user
          .save()
          .then(user => {
            course.buyNum += 1
            course.save().catch(err => {
              throw err
            })
            res.send({
              status: 1,
              msg: '报名成功',
              data: {
                price: course.price,
                buyNum: course.buyNum,
                courseName: course.courseName,
                description: course.description,
                courseURI: course.courseURI,
                id: courseId
              }
            })
          })
          .catch(err => {
            throw err
          })
      })
      .catch(err => {
        throw err
      })
  })
})

/**
 * @description user delete them already order course
 * @router /api/user/delCourse
 * @method POST
 */
router.post('/delCourse', (req, res) => {
  const data = req.body
  User.findById(data.userId).then(user => {
    for (let i = 0; i < user.applyCourse.length; i++) {
      if (data.courseId === user.applyCourse[i].id.toString()) {
        delArrOfOne(user.applyCourse, i, 1)
        break
      }
    }
    user.save().then(user => {
      Course.findById(data.courseId)
        .then(course => {
          course.buyNum = course.buyNum - 1
          course.save().catch(err => {
            throw err
          })
        })
        .catch(err => {
          throw err
        })
      res.send({
        status: 1,
        msg: '当前课程已从您的课程表中移除',
        data: null
      })
    })
  })
})

/**
 * @description 收藏课程接口
 * @router /api/user/collectCourse
 * @method GET
 */
router.get('/collectCourse', (req, res) => {
  const courseId = req.headers.courseid
  const userId = req.headers.userid
  User.findById(userId).then(user => {
    for (let i = 0; i < user.collect.length; i++) {
      if (courseId === user.collect[i].id.toString()) {
        return res.send({
          status: 0,
          msg: '您已收藏当前课程',
          data: null
        })
      }
    }
    Course.findById(courseId)
      .then(course => {
        user.collect.push({
          id: course._id,
          buyTime: getCurTime()
        })
        user
          .save()
          .then(user => {
            course.buyNum += 1
            course.save().catch(err => {
              throw err
            })
            res.send({
              status: 1,
              msg: '成功添加到收藏夹',
              data: {
                price: course.price,
                buyNum: course.buyNum,
                courseName: course.courseName,
                description: course.description,
                courseURI: course.courseURI,
                id: courseId
              }
            })
          })
          .catch(err => {
            throw err
          })
      })
      .catch(err => {
        throw err
      })
  })
})

/**
 * @description 查询教师信息
 * @router /api/user/userInfo
 * @method GET
 */
router.post('/userInfo', (req, res) => {
  const data = req.body
  User.findById(data.teacherId)
    .then(teacher => {
      res.send({
        status: 1,
        msg: '请求成功',
        data: {
          personalized: teacher.personalized,
          nickName: teacher.nickName,
          courseNum: teacher.myCourseNum,
          avatar: teacher.avatar
        }
      })
    })
    .catch(err => {
      throw err
    })
})

/**
 * @description 查询用户购买课程信息
 * @router /api/user/userBuy
 * @method GET
 */
router.get('/userBuy', async (req, res) => {
  const userId = req.headers.userid

  User.findById(userId).then(async user => {
    if (!user.applyCourse.length) {
      return res.send({
        status: 1,
        message: '您还没有购买任何课程',
        data: null
      })
    }
    let courseIdList = []

    for (let i = 0; i < user.applyCourse.length; i++) {
      courseIdList[i] = user.applyCourse[i].id
    }
    async.map(
      courseIdList,
      function (courseId, callback) {
        Course.findById(courseId)
          .then(course => {
            let courseSrc = {}
            let courseURI = course.courseURI
            let str = courseURI.substring(21, courseURI.length)
            let moviesArr = fs.readdirSync(`${uploadURI}${str}`)

            courseSrc.price = course.price
            courseSrc.buyNum = course.buyNum
            courseSrc.courseType = course.courseType
            courseSrc.evaluate = [...course.evaluate]
            courseSrc.chatMsg = [...course.chatMsg]
            courseSrc.id = course._id
            courseSrc.coursename = course.coursename
            courseSrc.description = course.description
            courseSrc.teacherId = course.teacherId
            courseSrc.courseURI = course.courseURI

            for (let i = 0; i < moviesArr.length; i++) {
              moviesArr[i] = courseURI + '/' + moviesArr[i]
            }
            courseSrc.src = [...moviesArr]
            callback(null, courseSrc)
          })
          .catch(err => {
            throw err
          })
      },
      (err, ret) => {
        if (err) {
          throw err
        }
        res.send({
          status: 1,
          msg: '请求成功',
          data: [...ret]
        })
      }
    )
  })
})

/**
 * @description 查询用户收藏课程信息
 * @router /api/user/userCollect
 * @method GET
 */
router.get('/userCollect', async (req, res) => {
  const userId = req.headers.userid

  User.findById(userId).then(async user => {
    let courseIdList = []

    for (let i = 0; i < user.collect.length; i++) {
      courseIdList[i] = user.collect[i].id
    }
    async.map(
      courseIdList,
      function (courseId, callback) {
        Course.findById(courseId)
          .then(course => {
            let courseSrc = {}
            let courseURI = course.courseURI
            let str = courseURI.substring(21, courseURI.length)
            let moviesArr = fs.readdirSync(`${uploadURI}${str}`)

            courseSrc.price = course.price
            courseSrc.buyNum = course.buyNum
            courseSrc.courseType = course.courseType
            courseSrc.evaluate = [...course.evaluate]
            courseSrc.chatMsg = [...course.chatMsg]
            courseSrc.id = course._id
            courseSrc.coursename = course.coursename
            courseSrc.description = course.description
            courseSrc.teacherId = course.teacherId
            courseSrc.courseURI = course.courseURI

            for (let i = 0; i < moviesArr.length; i++) {
              moviesArr[i] = courseURI + '/' + moviesArr[i]
            }
            courseSrc.src = [...moviesArr]
            callback(null, courseSrc)
          })
          .catch(err => {
            throw err
          })
      },
      (err, ret) => {
        if (err) {
          throw err
        }
        res.send({
          status: 1,
          msg: '请求成功',
          data: [...ret]
        })
      }
    )
  })
})

/**
 * @description 上传用户头像
 * @router /api/user/avatau
 * @method POST
 */
router.post('/avatar', (req, res) => {
  const form = new multiparty.Form()
  const data = req.headers

  form.encodeing = 'utf-8'
  form.uploadDir = uploadURI

  form.maxFileSize = 2048 * 1024
  form.parse(req, (err, fields, files) => {
    if (err) {
      throw err
    }

    User.findById(data.id).then(user => {
      if (!user) {
        return res.send({
          status: 0,
          msg: '当前用户不存在...',
          data: null
        })
      }

      if (!fs.existsSync(`${uploadURI}/avatars/${data.id}`)) {
        fs.mkdirSync(`${uploadURI}/avatars/${data.id}`)
      }

      if (fs.existsSync(`${uploadURI}/avatars/${data.id}`)) {
        fs.renameSync(files.file[0].path, `${uploadURI}/avatars/${data.id}/avatar.jpg`)
      }
      user.avatar = `${downloadURI}avatars/${data.id}/avatar.jpg`
      user
        .save()
        .then(user => {
          res.send({
            status: 1,
            msg: '头像上传成功',
            data: {
              avatar: user.avatar
            }
          })
        })
        .catch(err => {
          throw err
        })
    })
  })
})

/**
 * @description 修改用户信息
 * @router /api/user/modify
 * @method POST
 */
router.post('/modify', (req, res) => {
  const data = req.body

  User.findById(data.id).then(user => {
    if (!user) {
      return res.send({
        status: 1,
        msg: '当前用户不存在',
        data: null
      })
    }

    ;(user.nickName = data.nickName), (user.personalized = data.personalized)

    user
      .save()
      .then(ret => {
        res.send({
          status: 1,
          msg: '修改成功',
          data: {
            nickName: data.nickName,
            personalized: data.personalized
          }
        })
      })
      .catch(err => {
        throw err
      })
  })
})

/**
 * @description 返回当前用户已经购买的课程
 * @router /api/user/applyCourse
 * @method GET
 */
router.get('/applyCourse', (req, res) => {
  const data = req.query
  User.findById(data.id).then(user => {
    res.send({
      status: 1,
      msg: '查询成功',
      data: [...user.applyCourse]
    })
  })
})

module.exports = router
